<?php
require_once(dirname(dirname(__FILE__)) . '/app.php');
require_once(dirname(__FILE__) . '/paybank.php');
require_once dirname(__FILE__) ."/lib/WxPay.Api.php";
require_once dirname(__FILE__) ."/WxPay.JsApiPay.php";
require_once dirname(__FILE__) .'/log.php';

need_login();



if (is_post()) {
	$order_id = abs(intval($_POST['order_id']));
} else {
	if ( $_GET['id'] == 'charge' ) {
		redirect( WEB_ROOT. '/credit/index.php');
	}
	$order_id = $id = abs(intval($_GET['id']));
}
if(!$order_id || !($order = Table::Fetch('order', $order_id))) {
	redirect( WEB_ROOT. '/index.php');
}
if ( $order['user_id'] != $login_user['id']) {
	redirect( WEB_ROOT . "/team.php?id={$order['team_id']}");
}

$team = Table::Fetch('team', $order['team_id']);
team_state($team);

if (is_post() && $_POST['paytype'] ) {
	if($_POST['paytype'] == 'wxpay')
	{
		$uarray = array( 'service' => 'wxpay' );
		Table::UpdateCache('order', $order_id, $uarray);
	} else {
		$uarray = array( 'service' => pay_getservice($_POST['paytype']) );
		Table::UpdateCache('order', $order_id, $uarray);
		$order = Table::Fetch('order', $order_id);
		$order['service'] = pay_getservice($_POST['paytype']);
	}
	
}

if ( $_POST['paytype']!='credit' 
		&& $_POST['service']!='credit' 
		&& $team['team_type']=='seconds' 
		&& ($order['origin']>$login_user['money'])
		&& option_yes('creditseconds')
   ) {
	$need_money = ceil($order['origin'] - $login_user['money']);
	Session::Set('error', "秒杀项目仅可以使用余额付款，您的余额不足，还需要充值{$need_money}元才可以完成秒杀");
	redirect(WEB_ROOT . "/credit/charge.php?money={$need_money}");
}

//peruser buy count
if ($_POST && $team['per_number']>0) {
	$now_count = Table::Count('order', array(
		'user_id' => $login_user_id,
		'team_id' => $team['id'],
		'state' => 'pay',
	), 'quantity');
	$leftnum = ($team['per_number'] - $now_count);
	if ($leftnum <= 0) {
		Session::Set('error', '您购买本单产品的数量已经达到上限，快去关注一下其他产品吧！');
		redirect( WEB_ROOT . "/team.php?id={$id}"); 
	}
}

//payed order
if ( $order['state'] == 'pay' ) {  
	if ( is_get() ) {
		redirect(WEB_ROOT  . "/order/view.php?id={$order_id}");
		$user = Table::Fetch('user', $login_user['id'], 'id');
		if ($INI['sms']['buy']=='1' && Utility::IsMobile($user['mobile'])) {
			@session_start();
			$last_order_id = intval($_SESSION['last_order_id']);
			if($last_order_id != $order_id){
			$content = $INI['system']['sitename']." 团购项目：".$team['product']." 支付成功，感谢您的购买。";
			$ret = sms_send($user['mobile'], $content);
			$_SESSION['last_order_id'] = $order_id;
	
			}
		}
		die(include template('order_pay_success'));		
	} else {
		redirect(WEB_ROOT  . "/order/pay.php?id={$order_id}");
	}
}

$total_money = moneyit($order['origin'] - $login_user['money']);
if ($total_money<0) { 
	$total_money = 0; $order['service'] = 'credit'; 
} else if($_POST){
	$credit = moneyit($order['origin'] - $total_money);
	if ($order['credit']!=$credit) {
		Table::UpdateCache('order', $order_id, array('credit'=>$credit,));
	}
}

/* generate unique pay_id */
if (!($pay_id = $order['pay_id'])) {
	$randid = strtolower(Utility::GenSecret(4, Utility::CHAR_WORD));
	$pay_id = "go-{$order['id']}-{$order['quantity']}-{$randid}";
	Table::UpdateCache('order', $order['id'], array(
				'pay_id' => $pay_id,
				));
}


/* noneed pay where goods soldout or end */
if ($team['close_time']) {
	Session::Set('notice', '本单产品团购已结束，现在不能进行付款');
	redirect(WEB_ROOT  . "/team.php?id={$order['team_id']}");
}
/* end */

/* credit pay */
if ( $_POST['action'] == 'redirect' ) {
	redirect($_POST['reqUrl']);
}
elseif ( $_POST['service'] == 'credit' ) {
	if ( $order['origin'] > $login_user['money'] ){
		Table::Delete('order', $order_id);
		redirect( WEB_ROOT . '/order/index.php');
	}
	Table::UpdateCache('order', $order_id, array(
				'service' => 'credit',
				'money' => 0,
				'state' => 'pay',
				'credit' => $order['origin'],
				'pay_time' => time(),
				));
	$order = Table::FetchForce('order', $order_id);
	ZTeam::BuyOne($order);
	redirect( WEB_ROOT . "/order/pay.php?id={$order_id}");
}

$order['service'] = 'wxpay';
$pay_callback = "pay_team_{$order['service']}";


if ( function_exists($pay_callback) ) {
	var_dump($order['service'],3333);die();
	$payhtml = $pay_callback($total_money, $order);
	
	die(include template('order_pay'));
} else if($order['service'] == 'wxpay'){
	$total_money = $order['origin'];
	ini_set('date.timezone','Asia/Shanghai');
	$user = Table::Fetch('user', $login_user['id'], 'id');
	$openId = $user['open_id'];
	
	$card_credit = 0;
	if(isset($_POST['card_id']))
	{
		$card_id = trim($_POST['card_id']);
		if(!empty($card_id))
		{
			$card = DB::LimitQuery('card', array(
							'condition' => array(
								'consume' => 'N',
								'id' =>$card_id,
								'uid' => $login_user['id'],
								'begin_time <'.time().' and end_time>'.time().' and credit < '.$order['origin']
								),
							'ORDER BY addtime asc',
							'one' => true,
							));
			if($card)
			{
				$card_credit = $card['credit'];
				
				Table::UpdateCache('order', $order_id, array(
					'card_id' => $card_id,
					'card' => $card_credit,
				));
				
			}
		}
	}
	
	/**
	card_id
	card 
	Table::UpdateCache('order', $order_id, array(
				'service' => 'credit',
				'money' => 0,
				'state' => 'pay',
				'credit' => $order['origin'],
				'pay_time' => time(),
				));
	**/
	
	//var_dump($user);die();
	//初始化日志
	$logHandler= new CLogFileHandler(dirname(__FILE__) ."/logs/".date('Y-m-d').'.log');
	$log = Log::Init($logHandler, 15);
	
	//①、获取用户openid
	$tools = new JsApiPay();
	//$openId = $tools->GetOpenid();
	
	//②、统一下单
	$input = new WxPayUnifiedOrder();
	$input->SetBody(mb_substr($team['title'], 0, 30, 'utf-8'));
	$input->SetAttach(mb_substr($team['title'], 0, 30, 'utf-8'));
	$input->SetOut_trade_no($order['pay_id'].'-'.time());
	$input->SetTotal_fee( ceil(($order['origin']-$card_credit) *100));
	$input->SetTime_start(date("YmdHis"));
	$input->SetTime_expire(date("YmdHis", time() + 600));
	$input->SetGoods_tag("");
	if(isset($INI['system']['secsite']) && !empty($INI['system']['secsite']))
		$input->SetNotify_url($INI['system']['wwwprefix'].$INI['system']['secsite']."order/notify.php");
	else 
		$input->SetNotify_url($INI['system']['wwwprefix']."order/notify.php");
	
	$input->SetTrade_type("JSAPI");
	$input->SetOpenid($openId);
	
	
	$order_str = WxPayApi::unifiedOrder($input);
	//var_dump(ceil(($order['origin']-$card_credit) *100));die();
	//var_dump($order_str);die();
	//echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
	//printf_info($order);
	$jsApiParameters = $tools->GetJsApiParameters($order_str);
	//var_dump($jsApiParameters);die();
	//获取共享收货地址js函数参数
	$editAddress = $tools->GetEditAddressParameters();
	
	$pre_arr = '';
	if(isset($INI['system']['secsite']) && !empty($INI['system']['secsite']))
		$pre_arr = $INI['system']['secsite'];	
	else 
		$input->SetNotify_url($INI['system']['wwwprefix']."order/notify.php");
	
	if($order['is_pin'] == 1)
	{
		$refurl = $INI['system']['wwwprefix'].$pre_arr.'account/group.php?id='.$order['id'].'&show=1';
	} else {
		$refurl = $INI['system']['wwwprefix'].$pre_arr.'order/view.php?id='.$order['id'];
	}
	$backurl = $INI['system']['wwwprefix'].$pre_arr.'order/check.php?id='.$order['id'];
	//account/group.php?id=ZTMTQ4
	
	//var_dump($editAddress);die();
	die(include template('order_wxpay'));
}
else if ( $order['service'] == 'credit' ) {
	$total_money = $order['origin'];
	
	die(include template('order_pay'));
} 
else {
	Session::Set('error', '无合适的支付方式或余额不足');
	redirect( WEB_ROOT. "/team.php?id={$order_id}");
}
